package com.fanfan.shiroadmin.modules.sys.auth;

import com.fanfan.shiroadmin.common.exception.ServiceRuntimeException;
import com.fanfan.shiroadmin.common.utils.Constant;
import com.fanfan.shiroadmin.modules.sys.constant.SysConstant;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * token 生成器
 * @author DunFan.Liao
 * @date 2021/12/27 15:55
 */
public class TokenGenerator
{

    /**
     * 16进制值
     */
    private static final char [] hexCode = SysConstant.HEX_VALUE.toCharArray();

    public static String generateValue()
    {
        return generateValue(UUID.randomUUID().toString());
    }

    /**
     * 功能描述：获取16进制字符数组
     * @param data 需要转换的字符数组
     * @return 16进制字符数组
     * @author DunFan.Liao
     * @date 2021/12/27 19:54
     */
    public static String toHexString(byte[] data)
    {
        if (data == null)
        {
            return null;
        }
        StringBuilder buffer = new StringBuilder(data.length * 2);
        for (byte b : data)
        {
            buffer.append(hexCode[(b >> 4) & 0xF]);
            buffer.append(hexCode[(b & 0xF)]);
        }
        return buffer.toString();
    }

    public static String generateValue(String param)
    {
        try {
            MessageDigest digest = MessageDigest.getInstance(Constant.MD5);
            digest.reset();
            digest.update(param.getBytes());
            byte[] messageDigest = digest.digest();
            return toHexString(messageDigest);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new NegativeArraySizeException("找不到指定的算法：" + Constant.MD5 + e);
        } catch (Exception e)
        {
            throw new ServiceRuntimeException("生成token失败", e);
        }
    }
}
